package com.woniu.service.impl;

import com.woniu.dao.PermissionDao;
import com.woniu.pojo.Permission;
import com.woniu.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public List<Permission> getPermissions() {
        List<Permission> permissionList = permissionDao.selectByExample(null);
        Map<Integer,Permission> permissionMap = new HashMap<>();
        for(Permission permission:permissionList){
            permissionMap.put(permission.getPid(),permission);
        }
        List<Permission> rootList = new ArrayList<>();

        for(Permission permission:permissionList){
            if(permission.getParentid()==null){
                rootList.add(permission);
                permission.setOpen(true);
            }else{
                permissionMap.get(permission.getParentid()).getChildren().add(permission);
            }
        }
        return rootList;
    }

    @Override
    public void save(Permission permission) {
        permissionDao.insertSelective(permission);
    }
}
